package edu.uoc.tfc.service.security;

import org.acegisecurity.DisabledException;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UserDetailsService;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.springframework.dao.DataAccessException;

import edu.uoc.tfc.ServiceLocator;
import edu.uoc.tfc.dto.security.UserVO;

public class UserDetailsServiceImpl implements UserDetailsService {

	
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException, DataAccessException {

    	SecurityService service = ServiceLocator.instance().getSecurityService();
        final UserVO userDetailsVO = service.getUsuariDetall(username);
        if (userDetailsVO == null) {
            throw new UsernameNotFoundException("");
        }else{
        	if (!userDetailsVO.getActive()){
        		throw new DisabledException("");
        	}
        }
        return new UserDetails() {
			
			private static final long serialVersionUID = 1L;

			public boolean isEnabled() {
				return userDetailsVO.getActive();
			}
			
			public boolean isCredentialsNonExpired() {
				return true;
			}
			
			public boolean isAccountNonLocked() {
				return true;
			}
			
			public boolean isAccountNonExpired() {
				return true;
			}
			
			public String getUsername() {
				return userDetailsVO.getUserId();
			}
			
			public String getPassword() {
				return userDetailsVO.getPassword();
			}
			
			public GrantedAuthority[] getAuthorities() {
				GrantedAuthority[] authorities = new GrantedAuthorityImpl[1];
	            authorities[0] = new GrantedAuthorityImpl(userDetailsVO.getRolVO().getDescription());
		        return authorities;				
			}
		};
        
    }
}